package com.teach.servlet;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.teach.service.impl.Const;

import cn.hutool.captcha.AbstractCaptcha;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.generator.RandomGenerator;

public class CodeServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		int w = 200;
		int h = 100;
		int len = 4;
		w = Integer.valueOf(req.getParameter("w"));
		h = Integer.valueOf(req.getParameter("h"));
		len = Integer.valueOf(req.getParameter("len"));

		try {
			w = Integer.valueOf(req.getParameter("w"));
		} catch (Exception ex) {
		}
		try {
			h = Integer.valueOf(req.getParameter("h"));
		} catch (Exception ex) {
		}
		try {
			len = Integer.valueOf(req.getParameter("len"));
		} catch (Exception ex) {
		}
		if (w < 100 || w > 1000) {
			w = 200;

		}
		if (h < 20 || h > 200) {
			h = 100;
		}
		if (len < 1 || len > 10) {
			len = 4;
		}

		AbstractCaptcha captcha = null;
		// 定义图形验证码的长、宽、验证码字符数、干扰线宽度
		captcha = CaptchaUtil.createShearCaptcha(w, h, len, 4);
		RandomGenerator randomGenerator = new RandomGenerator("0123456789", len);
		captcha.setGenerator(randomGenerator);
		req.getSession().setAttribute(Const.CODE_NAME, captcha.getCode());
		resp.reset();
		resp.setContentType("image/png");
		captcha.write(resp.getOutputStream());
		resp.flushBuffer();
	}
}
